import dayjs from 'dayjs';
import axios from 'axios';

export const getEnv = (key: string, defaultValue?: string): string => {
    const value = process.env[key] || defaultValue;
    if (!value) {
        throw new Error(`Missing environment variable: ${key}`);
    }
    return value;
};

/**
 * 获取格式化后的日期
 * @param format 日期格式，默认为 'YYYYMMDD'
 * @returns 格式化后的日期字符串
 */
export function getFormattedDate(format: string = 'YYYYMMDD'): string {
    // 获取当前日期并根据传入格式进行格式化
    return dayjs().format(format);
}

/**
* 移除字符串中的 <div> 标签。
* @param input 包含 <div> 标签的字符串
* @returns 移除 <div> 标签后的字符串，如果发生错误则返回空字符串
*/
export function removeDivTags(input: string): string {
    try {
        return input.replace(/<\/?div[^>]*>/g, '');
    } catch (error) {
        return '';
    }
}


export function isInList(targetList: string[], targetString: string): boolean {
    return targetList.includes(targetString);
}


interface RobotMessage {
    msgtype: string;
    text: {
        mentioned_mobile_list: string[];
        content: string;
    };
}

export async function sendToWeChat(mentionedMobileList: string[], content: string, robotApi: string) {
    const robotMessage: RobotMessage = {
        msgtype: 'text',
        text: {
            mentioned_mobile_list: mentionedMobileList,
            content: content
        }
    };

    await axios.post(robotApi, robotMessage, {
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((response: any) => {
        console.log('Message sent successfully', response.data);
    }).catch((error: any) => {
        console.error('Error sending message', error);
    });
}


interface Article {
    title: string;
    description: string;
    url: string;
    picurl: string;
}

interface NewsMessage {
    msgtype: string;
    news: {
        articles: Article[];
    };
}

export async function sendWeChatArticle(robotApi: string, pic: string, articleLink: string, title: string, desc: string) {
    const body: NewsMessage = {
        msgtype: 'news',
        news: {
            articles: [
                {
                    title: title,
                    description: desc,
                    url: articleLink,
                    picurl: pic
                }
            ]
        }
    };

    await axios.post(robotApi, body, {
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log('Article sent successfully', response.data);
    }).catch(error => {
        console.error('Error sending article', error);
    });
}


export function convertToUnixTimestamp(dateString: string): number{
    const date = new Date(dateString);
    return date.getTime();
}   